import React, { useEffect, useState, useContext } from 'react';
import {
  Table,
  Button,
  Input,
  Card,
  Modal,
  Form,
  Message,
  Popconfirm,
  Select,
  Badge,
  Image,
  Tooltip,
  Tag,
  Radio,
  PaginationProps,
  Grid,
  Space,
} from '@arco-design/web-react';
import { IconLink, IconPlus } from '@arco-design/web-react/icon';
import { GlobalContext } from '@/context';

import styles from './style/index.module.less';
import {
  getListRecommend,
  createRecommend,
  updateRecommend,
  removeRecommend,
} from '@/api/site/right';

import dayjs from 'dayjs';
import copy from 'copy-to-clipboard';
import UploadImage from '@/components/UploadImage';

const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};

const showPositions = [
  '首页',
  '文章',
  '文章详情',
  '归档',
  '分类',
  '分类详情',
  '标签',
  '标签详情',
  '关于',
];

const showPositionsColorObj = {
  首页: 'blue',
  文章: '#87d068',
  文章详情: 'volcano',
  归档: '#f50',
  分类: 'gold',
  分类详情: 'lime',
  标签: '#108ee9',
  标签详情: 'cyan',
  关于: '#2db7f5',
};

const projects = [
  {
    key: '1',
    value: '电影',
  },
  {
    key: '2',
    value: '电视剧',
  },
  {
    key: '3',
    value: '音乐',
  },
];
function Tab3() {
  const [form] = Form.useForm();
  const [formModal] = Form.useForm();
  const { Row, Col } = Grid;
  const [title, setTitle] = useState('添加标签');
  const [data, setData] = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});
  const { lang } = useContext(GlobalContext);
  const colSpan = lang === 'zh-CN' ? 8 : 12;
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const copyLink = (msg) => {
    if (copy(msg)) {
      Message.success('复制成功');
    } else {
      Message.error('复制失败');
    }
  };

  const columns = [
    {
      title: '类别',
      dataIndex: 'project',
      render: (_, record) => {
        const colorObj = {
          1: 'purple',
          2: 'pink',
          3: '#52c41a',
        };
        const text = projects[+record.project - 1].value;
        return (
          <Badge
            dotStyle={{ background: colorObj[record.project] }}
            text={text}
          ></Badge>
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '封面',
      dataIndex: 'cover',
      render: (_, record: any) => {
        return <Image width={50} height={50} src={record.cover}></Image>;
      },
    },
    {
      title: '链接',
      dataIndex: 'link',
      render: (_, record) => {
        return (
          <Tooltip content={record.link}>
            <a style={{ cursor: 'pointer' }}>
              <IconLink onClick={() => copyLink(record.link)} />
            </a>
          </Tooltip>
        );
      },
    },
    {
      title: 'VIP',
      dataIndex: 'isVip',
      render: (_, record) => {
        return record.isVip ? '是' : '否';
      },
    },
    {
      title: '展示位置',
      dataIndex: 'showPosition',
      render: (_, record) => {
        let result = [];
        for (let i = 0; i < record.showPosition.length; i += 3) {
          result.push(record.showPosition.slice(i, i + 3)); // i=0 0-3 i=3 3-6
        }
        return result.map((item, index) => {
          return (
            <div style={{ marginBottom: 10 }} key={index}>
              {item.map((sub) => (
                <Tag
                  style={{ marginRight: 10 }}
                  key={sub}
                  color={showPositionsColorObj[sub]}
                >
                  {sub}
                </Tag>
              ))}
            </div>
          );
        });
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (x) => dayjs(x).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      render: (x) => (x ? dayjs(x).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },

    {
      title: '操作',
      dataIndex: 'operations',
      render: (_, record) => (
        <div className={styles.operations}>
          <Button
            disabled={record.status}
            onClick={() => onUpdate(record)}
            type="text"
            size="small"
          >
            修改
          </Button>
          <Popconfirm
            disabled={record.status}
            title="Are you sure you want to delete?"
            onOk={() => onDelete(record)}
          >
            <Button
              disabled={record.status}
              type="text"
              status="danger"
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  // 获取表格数据
  async function fetchData() {
    console.log(pagination);
    const { current, pageSize } = pagination;
    setLoading(true);
    const params = {
      page: current,
      pageSize,
      ...formParams,
    };
    try {
      console.log(params);
      const res: any = await getListRecommend(params);
      console.log(res);
      if (res.code === 200) {
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      } else {
      }
    } catch (error) {
      console.error(error);
    }
  }

  function onChangeTable(pagination) {
    setPatination(pagination);
  }

  const onSelectChange = (project) => {
    console.log(project);
    console.log(form.getFields());
    setFormParams(form.getFields());
  };

  // 新增
  const addClick = () => {
    setVisible(true);
  };

  // 取消新增
  const onCancel = () => {
    formModal.resetFields();
    setVisible(false);
  };

  // 确认新增
  const onOk = async () => {
    await formModal.validate();
    const data = formModal.getFields(); // {name:'123'}
    console.log('data', data);

    if (data.imgs && data.imgs.length) {
      data.cover = data.imgs[0].imgUrl;
      data.link = data.imgs[0].link;
    }

    let func = createRecommend;
    if (data._id) {
      func = updateRecommend;
    }

    const res: any = await func(data);
    if (res.code === 200) {
      onCancel();
      fetchData();
      Message.success(res.msg);
    } else {
      Message.success('添加失败，请重试！');
    }
  };

  //修改
  const onUpdate = (row) => {
    row.imgs = [
      {
        imgUrl: row.cover,
        link: row.link,
      },
    ];
    formModal.setFieldsValue(row);
    setTitle('修改标签');
    setVisible(true);
  };

  // 删除
  const onDelete = async (row) => {
    setLoading(true);
    const res: any = await removeRecommend(row);
    if (res.code === 200) {
      Message.success(res.msg);
      fetchData();
    } else {
      Message.error('删除失败，请重试！');
    }
    setLoading(false);
  };

  return (
    <div className={styles.container}>
      <Card bordered={false}>
        <div className={styles['search-form-wrapper']}>
          <Form
            form={form}
            className={styles['search-form']}
            labelAlign="left"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 16 }}
          >
            <Row gutter={24}>
              <Col span={colSpan}>
                <Form.Item label="分类名称" field="project">
                  <Select
                    style={{ width: 300 }}
                    placeholder="请选择推荐项目"
                    onChange={onSelectChange}
                    defaultValue=""
                  >
                    {[
                      {
                        key: '',
                        value: '全部',
                      },
                      ...projects,
                    ].map((item) => (
                      <Select.Option key={item.key} value={item.key}>
                        {item.value}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles['button-group']}>
          <Space>
            <Button type="primary" icon={<IconPlus />} onClick={addClick}>
              新建
            </Button>
          </Space>
        </div>
        <Table
          rowKey="_id"
          loading={loading}
          onChange={onChangeTable}
          pagination={pagination}
          columns={columns}
          data={data}
        />

        <Modal
          title={<div style={{ textAlign: 'left' }}> {title} </div>}
          visible={visible}
          onOk={onOk}
          confirmLoading={confirmLoading}
          onCancel={onCancel}
        >
          <Form {...formItemLayout} form={formModal}>
            <Form.Item
              label="推荐项目"
              field="project"
              rules={[{ required: true, message: '请选择推荐项目' }]}
            >
              <Select placeholder="请选择推荐项目">
                {projects.map((item) => (
                  <Select.Option key={item.key} value={item.key}>
                    {item.value}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              label="名称"
              field="name"
              rules={[{ required: true, message: '请输入名称' }]}
            >
              <Input placeholder="请输入名称" />
            </Form.Item>

            <Form.Item
              label="展示位置"
              field="showPosition"
              rules={[{ required: true, message: '请选择展示位置' }]}
            >
              <Select mode="multiple" placeholder="请选择展示位置">
                {showPositions.map((option) => (
                  <Select.Option key={option} value={option}>
                    {option}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="平台"
              field="platform"
              rules={[{ required: true, message: '请输入平台' }]}
            >
              <Input placeholder="请输入平台" />
            </Form.Item>

            <Form.Item label="是否需要VIP" field="isVip">
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              label="封面/链接"
              field="imgs"
              rules={[{ required: true, message: '请上传封面/链接' }]}
            >
              <UploadImage />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
}

export default Tab3;
